package com.xiaoxiang.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.xiaoxiang.common.exception.CommonException;
import com.xiaoxiang.common.exception.DefaultException;
import com.xiaoxiang.common.result.ResultCodeEnum;
import com.xiaoxiang.pay.entity.PayOrder;
import com.xiaoxiang.pay.enumeration.PayStateEnum;
import com.xiaoxiang.pay.param.CreateOrderParam;
import com.xiaoxiang.pay.result.CreateOrderResult;
import com.xiaoxiang.pay.result.PayResult;
import com.xiaoxiang.pay.service.PayOrderService;
import com.xiaoxiang.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: haha
 * @date: 2022/4/2 11:01
 */
@Service("alipayService")
@Slf4j
public class AlipayServiceImpl implements PayService {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private PayOrderService payOrderService;


    @Value("${alipay.defaultReturnUrl}")
    private String defaultReturnUrl;

    @Value("${alipay.defaultNotifyUrl}")
    private String defaultNotifyUrl;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public CreateOrderResult createOrder(CreateOrderParam param) {
        if (param.getPayeeUserId().equals(param.getDraweeUserId())) {
            throw new DefaultException("付款人与收款人不能为同一人");
        }
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(param, payOrder);
        payOrderService.save(payOrder);
        return CreateOrderResult.builder()
                .orderId(payOrder.getId())
                .form(generatePayRequest(payOrder.getId().toString(), param.getAmount(), param.getSubject()))
                .build();
    }

    @Override
    public void resultCallBack(Long orderId, PayStateEnum payStateEnum) {
        PayOrder order = PayOrder.builder().id(orderId).state(payStateEnum).build();
        payOrderService.updateById(order);
        PayResult payResult = new PayResult();
        payResult.setOrderId(orderId);
        if (payStateEnum.equals(PayStateEnum.OK)) {
            payResult.setSuccess(true);
        } else {
            payResult.setSuccess(false);
        }
        rocketMQTemplate.send("pay_result", new GenericMessage<>(payResult));
    }

    /**
     * 生成支付跳转请求
     *
     * @param orderId 订单id
     * @param amount  金额
     * @param subject 主题
     * @return form表单
     */
    private String generatePayRequest(String orderId, String amount, String subject) {
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(defaultReturnUrl);
        alipayRequest.setNotifyUrl(defaultNotifyUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", amount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "QUICK_WAP_WAY");
        alipayRequest.setBizContent(bizContent.toJSONString());
        String form;
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new CommonException(ResultCodeEnum.SYSTEM_EXCEPTION, e.getMessage());
        }
        return form;
    }

}
